package thread;

import java.util.concurrent.*;

import static sun.swing.SwingUtilities2.submit;

//Callable 含返回值的 多线程

/**
 * 实现Callable接口，需要返回值类型
 * 重写call方法 需要抛出异常
 * 创建目标对象 TestCallable c1 = new TestCallable();
 * 创建执行服务 ExecutorService service = Executors.newFixedThreadPool(3);
 * 提交执行 Future<String> r1 = service.submit(c1);
 * 获取结果 String rs1 = r1.get();
 * 关闭服务 service.shutdown();
 */
public class TestCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("Callable 执行了");
        return "一个返回值"+Thread.currentThread().getName();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable c1 = new TestCallable();
        TestCallable c2 = new TestCallable();
        TestCallable c3 = new TestCallable();
        //创建服务
        ExecutorService service = Executors.newFixedThreadPool(3);
        //提交执行
        Future<String> r1 = service.submit(c1);
        Future<String> r2 = service.submit(c2);
        Future<String> r3 = service.submit(c3);
        //获取结果
        String rs1 = r1.get();
        String rs2 = r2.get();
        String rs3 = r3.get();
        //关闭服务
        service.shutdown();
        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
    }
}
